import { getProto, getApiJson } from './utils'
import { rollup } from 'rollup'
import type { OutputOptions, InputOptions, InputOption } from 'rollup'
import { nodeResolve } from '@rollup/plugin-node-resolve'
import commonjs from '@rollup/plugin-commonjs'
import typescript from 'rollup-plugin-typescript2';
import { resolve } from 'path';
import { isExists, copyDir } from "./fsV"
import write from 'write'
import { dirname } from 'path'
import { fileURLToPath } from 'url'
import { TSBufferProtoGenerator } from 'tsbuffer-proto-generator';
import log from "#utils/log"
import replace from '@rollup/plugin-replace';
import { clearFormat } from "../src/utils/pubFunction"
import { readFileSync } from 'fs'
// import terser from '@rollup/plugin-terser';
//打包API文件
export async function BuildApi(inputUrl: Record<string, string>, common: string[]) {
    log.info("[shim:unicloud]开始打包API文件")
    //打包plugins函数
    let plugins = [
        nodeResolve(),
        commonjs({
            ignoreDynamicRequires: true
        })
    ]
    if (common.length > 0) {
        plugins.push(replace({
            values: {
                "global.common": "require"
            },
            preventAssignment: true
        }))
    }
    if (process.env.ISTS === 'ts') {
        plugins.unshift(typescript())
    }
    const inputs: InputOptions = {
        input: inputUrl as InputOption,//入口文件
        plugins
    }
    const bundle = await rollup(inputs);
    const outputOptions: OutputOptions = {
        dir: resolve(process.cwd(), process.env.UNICLOUDURL + "/module"), //打包后的存放文件
        format: 'cjs', //输出格式 amd es6 iife umd cjs
    }
    // 或者将bundle写入磁盘
    await bundle.write(outputOptions);
}


//打包路由文件
export async function BuildRouter(inputUrl: string, common: string[]) {
    log.info("[shim:unicloud]开始打包路由文件")
    //打包plugins函数
    let plugins = [
        nodeResolve(),
        commonjs({
            ignoreDynamicRequires: true
        })
    ]
    if (common.length > 0) {
        plugins.push(replace({
            values: {
                "global.common": "require"
            },
            preventAssignment: true
        }))
    }
    if (process.env.ISTS === 'ts') {
        plugins.unshift(typescript())
    }
    const inputs: InputOptions = {
        input: inputUrl,// 入口文件
        plugins
    }
    const bundle = await rollup(inputs);
    const outputOptions: OutputOptions = {
        file: resolve(process.cwd(), process.env.UNICLOUDURL + "/index.js"), //打包后的存放文件
        format: 'cjs', //输出格式 amd es6 iife umd cjs
    }
    // 或者将bundle写入磁盘
    await bundle.write(outputOptions);
}


// 复制工具文件
export function copyPlugin(out_input?: string) {
    const input_url = out_input ? out_input : process.env.UNICLOUDURL
    //获取当前文件夹路径
    const __dirname = dirname(fileURLToPath(
        import.meta.url))
    //相对当前文件的plugins文件夹
    const plugins_src = resolve(__dirname, "../plugins")
    //复制plugins文件到文件夹
    copyDir(plugins_src, resolve(process.cwd(), `${input_url}/plugins`))
}

// 生成json参数文件
export async function writeGenerator(apiObj: Record<string, string>, out_input?: string) {
    const generator = new TSBufferProtoGenerator({
        keepComment: false
    });
    let list: string[] = []
    Object.keys(apiObj).forEach(item => {
        const apiurl = apiObj[item]
        // 获取API对应的proto文件
        const proto_url = apiurl.substring(0, apiurl.lastIndexOf(process.env.SPLITSTR as string)) + `${process.env.SPLITSTR}proto.ts`
        // 判断文件是否存在
        if (isExists(proto_url) === "file") {
            list.push(`${proto_url}`)
        }
    })
    if (list.length > 0) {
        log.info("[shim:unicloud]开始生成校验文件")
        const protoList = await generator.generate(list)
        let json_file: Record<string, unknown> = {}
        Object.keys(apiObj).forEach(item => {
            const api = item.replaceAll(".", "/")
            json_file[item] = protoList[`${process.env.APIINPUT}/${api}/proto/ReqData`]
        })
        const outInput = out_input ? out_input : (process.env.UNICLOUDURL as string) // 生成地址，默认生成到unicloud文件夹
        write.sync(resolve(process.cwd(), outInput) + "/schema/TSBuffer.json", JSON.stringify(json_file));
    }
}

// 生成校验文件
export async function writeValidate(apiObj: Record<string, string>, out_input?: string) {
    const generator = new TSBufferProtoGenerator({
        keepComment: true
    });
    let list: { router: string, key: string, proUrl: string }[] = []
    Object.keys(apiObj).forEach(async item => {
        const apiurl = apiObj[item]
        // 获取接口内容
        const content = clearFormat(readFileSync(apiurl, 'utf8'));
        if (content.length === 0) return;
        // 格式化后的API对象数据
        const ApiModule = getApiJson(content)
        // 是否需要生成文件
        if (ApiModule.validate) {
            // 获取API对应的proto文件
            const proto_url = apiurl.substring(0, apiurl.lastIndexOf(process.env.SPLITSTR as string)) + `${process.env.SPLITSTR}proto.ts`
            // 判断文件是否存在
            if (isExists(proto_url) === "file") {
                list.push({
                    router: item.replaceAll(".", "/"),
                    key: `${process.env.APIINPUT}/${item.replaceAll(".", "/")}/proto/ReqData`,
                    proUrl: `${proto_url}`
                })
            }
        }
    })
    if (list.length > 0) {
        log.info("[shim:unicloud]开始生成校验文件")
        const protoList = await generator.generate(list.map(item => item.proUrl))
        let json_file: Record<string, unknown> = {}
        list.forEach(item => {
            json_file[item.router] = getProto(protoList[item.key]);
        })
        const outInput = out_input ? out_input : (process.env.UNICLOUDURL as string) // 生成地址，默认生成到unicloud文件夹
        write.sync(resolve(process.cwd(), outInput) + "/schema/TSBuffer.json", JSON.stringify(json_file));
    }
}
